﻿using Arch.Core;
using Meow.Core.Graphics;
using Meow.Core.Input;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Input;
using Myra.Graphics2D.UI;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Meow.Core.Simulation;

public class test_CameraControlSystem : ECS_System, IUpdateSystem
{
    Label info;
    QueryDescription cameraQuery = new QueryDescription()
                                        .WithAll<SimpleCamera>();
    public test_CameraControlSystem(World world, Scene scene, Label info) : base(world, scene)
    {
        this.info = info;
    }

    void IUpdateSystem.Update(GameTime gameTime, float totalElapsedTime, float scaleFactor)
    {
        float rotSpeed = 60f;
        float speed = 0.2f;
        var rot = new Vector2();
        var move = new Vector3();

        info.Text = "";

        if (MouseUtil.PointerMoved)
        {
            rot = MouseUtil.PointerDelta.ToVector2() * rotSpeed * (float)gameTime.ElapsedGameTime.TotalSeconds / new Vector2(InputHandler.WindowWidth, InputHandler.WindowHeight);
        }

        if (Keyboard.GetState().IsKeyDown(Keys.D))
            move.X += speed;
        if (Keyboard.GetState().IsKeyDown(Keys.A))
            move.X -= speed;

        if (Keyboard.GetState().IsKeyDown(Keys.W))
            move.Y += speed;
        if (Keyboard.GetState().IsKeyDown(Keys.S))
            move.Y -= speed;

        if (Keyboard.GetState().IsKeyDown(Keys.Space))
            move.Z += speed;
        if (Keyboard.GetState().IsKeyDown(Keys.LeftControl))
            move.Z -= speed;

        // lock the camera if the cursor is active
        if (Screen.ShowCursor)
        {
            move = Vector3.Zero;
            rot *= 0.16f;
        }

        world.Query(cameraQuery, (ref SimpleCamera cam) =>
        {
            var camUp = cam.Up;
            var camRight = cam.Right;
            var camFront = cam.Forward;
            //var rotquat = Quaternion.CreateFromAxisAngle(camUp, -rot.X) * Quaternion.CreateFromAxisAngle(camRight, -rot.Y);
            //cam.Up = Vector3.Transform(Vector3.Up, Matrix.CreateFromQuaternion(Quaternion.CreateFromAxisAngle(camRight, -rot.Y)));
            //var rotquat = Quaternion.CreateFromYawPitchRoll(rot.X,rot.Y,0);
            cam.Yaw += rot.X;
            cam.Pitch += rot.Y;
            cam.Position += camRight * move.X + camFront * move.Y + camUp * move.Z;

            //cam.Rotation = cam.Rotation.ToEuler().ToQuaternion();
            if (Screen.ShowCursor)
                cam.LookAt(System.Numerics.Vector3.Zero);

            info.Text += "Camera: \n Pos: " + cam.Position + "\n Yaw: " + MathHelper.ToDegrees(cam.Yaw) + "\n Pitch: " + MathHelper.ToDegrees(cam.Pitch) + "\n EntitiesInSight: " + cam.EntitiesInSight.Count + "\n";
        });


    }
}
